/**
 * @description url转dataUrl
 */

// 方法1:
async function loadImageToBlobUrl(url, imageType = "png") {
  const imgData = await fetch(url).then((res) => res.arrayBuffer());
  const imgUrl = window.URL.createObjectURL(
    new Blob([imgData], { type: "image/" + imageType })
  );
  return imgUrl;
}

//方法2:
function loadImageToDataUrl(url, imageType = "png") {
  return new Promise((resolve, reject) => {
    let img = new Image();
    img.setAttribute("crossOrigin", "");
    img.src = url;
    img.onload = () => {
      img.onload = null;
      img.onerror = null;

      const canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      const ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, img.width, img.height);
      const dataURL = canvas.toDataURL("image/" + imageType);
      resolve(dataURL);
    };
    img.onerror = (e) => {
      console.log("loadImageToDataUrl", e);
      img.onload = null;
      img.onerror = null;
      resolve(null);
    };
  });
}
